package cn.wm.server;

import cn.hutool.log.Log;
import cn.hutool.log.StaticLog;
import cn.wm.codec.MessageDecoder;
import cn.wm.codec.MessageEncoder;
import cn.wm.constant.ProtocolConstants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;

/**
 * Server
 *
 * @author Administrator
 * @version 1.0
 * 2021/6/25 0:04
 **/
public class Server {

    private final static Log log = StaticLog.get();

    public static void main(String[] args) {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker)//绑定两个工作线程组
                    .channel(NioServerSocketChannel.class)                  //设置NIO的模式
                    .option(ChannelOption.SO_BACKLOG, 10240)        //设置TCP缓冲区
                    .option(ChannelOption.SO_RCVBUF, 1024 * 32)    // 设置接受数据的缓存大小
                    .option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)   // 设置保持连接
                    .option(ChannelOption.SO_SNDBUF, 1024 * 32)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(channelInitializer());
            ChannelFuture future = bootstrap.bind(ProtocolConstants.SERVER_PORT).sync();
            log.info("Server start... listen port:{}",ProtocolConstants.SERVER_PORT);
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    private static ChannelInitializer<SocketChannel> channelInitializer() {
        return new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                ChannelPipeline pipeline = channel.pipeline();
                pipeline.addLast("frameDecoder", new MessageDecoder());
                pipeline.addLast("frameEncoder", new MessageEncoder());
                pipeline.addLast("readTimeoutHandler",new ReadTimeoutHandler(50));
                //<todo>
                pipeline.addLast("loginAuthRespHandler",new LoginAuthRespHandler());
                pipeline.addLast("heartBeatRespHandler", new HeartBeatRespHandler());
                pipeline.addLast(new ServerHandler());
            }
        };
    }
}
